using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace TripleMatch
{
    public class GameDialogUI : MonoBehaviour
    {
        [SerializeField] Button m_buttonBack;
        [SerializeField] Transform m_cubeParent;
        [SerializeField] Transform m_cubeRecycleParent;

        [SerializeField] LevelObj m_cube;

        private List<LevelObj> m_cubeList;
        private List<LevelObj> m_recycleCubeList;

        private void Start()
        {
            m_buttonBack.onClick.AddListener(OnClickBack);
        }

        private void OnClickBack()
        {
            LevelManager.S.DestroyGame();
        }

        private void OnEnable()
        {
            if (m_cubeList == null) m_cubeList = new List<LevelObj>();
            if (m_recycleCubeList == null) m_recycleCubeList = new List<LevelObj>();
        }

        private void OnDisable()
        {
            while (m_cubeList.Count > 0)
            {
                RecycleCubeObj(m_cubeList[0]);
            }
        }

        private void RecycleCubeObj(LevelObj levelObj)
        {
            m_cubeList.Remove(levelObj);
            m_recycleCubeList.Add(levelObj);
            levelObj.gameObject.SetActive(false);
            levelObj.transform.SetParent(m_cubeRecycleParent);
        }

        private LevelObj GetCubeObj()
        {
            if (m_recycleCubeList.Count > 0)
            {
                LevelObj levelObj = m_recycleCubeList[0];
                levelObj.transform.SetParent(m_cubeParent);
                m_recycleCubeList.Remove(levelObj);
                m_cubeList.Add(levelObj);

                return levelObj;
            }
            else
            {
                GameObject gameObject = GameObject.Instantiate(m_cube.gameObject, m_cubeParent);
                LevelObj levelObj = gameObject.GetComponent<LevelObj>();
                m_cubeList.Add(levelObj);

                return levelObj;
            }
        }

        public void RefreshGameUI(List<int> indexList, int hideIndex)
        {
            for (int i = 0; i < m_cubeList.Count; i++)
            {
                m_cubeList[i].InitLevelObj(-2, indexList[i], null);
            }

            for (int i = m_cubeList.Count; i < indexList.Count; i++)
            {
                LevelObj levelObj = GetCubeObj();
                levelObj.InitLevelObj(-2, indexList[i], null);
                levelObj.gameObject.SetActive(true);
            }

            if (hideIndex != -1)
            {
                int hideCount = 3;
                while (hideCount > 0)
                {
                    RecycleCubeObj(m_cubeList[hideIndex]);
                    hideCount--;
                }
            }

        }
    }
}
